class MysqlConnection {
    constructor(connection) {
        this.conn = connection;
    }

    query(sql, param=null, oneRow=false) {
        const self = this;
        return new Promise(function (resolve, reject) {
            self.conn.query(sql, param, (err, results, fields)=>{
                if(err){
                    reject(`${sql}[${param}]:${err}`);
                }
                else{
                    if (oneRow) {
                        if (results && results.length) {
                            results = results[0];
                        } else {
                            results = null;
                        }
                    }
                    resolve(results);
                }
            });
        })
    }

    execute(sql, param=null) {
        const self = this;
        return new Promise(function (resolve, reject) {
            self.conn.query(sql, param, (err)=>{
                if(err){
                    reject(`${sql}[${param}]:${err}`);
                }
                else{
                    resolve(null);
                }
            });
        })
    }

    close() {
        this.conn.end();
        this.conn = null;
    }

    release() {//不关闭连接将其放回池中
        this.conn.release();
        this.conn = null;
    }

    destroy() {//关闭连接并将其从池中删除
        this.conn.destroy();
        this.conn = null;
    }

    beginTransaction() {
        const self = this;
        return new Promise(function (resolve, reject) {
            self.conn.beginTransaction((err)=>{
                if (err) {
                    reject(err);
                } else {
                    resolve(null);
                }
            });
        })
    }
    
    commit() {
        const self = this;
        return new Promise(function (resolve, reject) {
            self.conn.commit((err)=>{
                if (err) {
                    reject(err);
                } else {
                    resolve(null);
                }
            });
        })
    }

    rollback() {
        const self = this;
        return new Promise(function (resolve, reject) {
            self.conn.rollback((err)=>{
                if (err) {
                    reject(err);
                } else {
                    resolve(null);
                }
            });
        })
    }
}

module.exports = MysqlConnection;